//
//  CalendarView.swift
//  Aiwei
//
//  Created by zhu xietong on 2018/1/16.
//  Copyright © 2018年 zhu xietong. All rights reserved.
//

import Foundation
import Eelay
import JTAppleCalendar
import JoLoading

class OneDayCalendarView:JoView{
    var validSelectCheck:(Date)->Bool = {_ in return true}
    var confirmDate:(Date)->Void = {_ in}
    
    var scrollToedDate:Date?
    
    open lazy var calendarView: JTACMonthView = { [unowned self] in
        
        // FIXME: prevent Swift bug, lazy property initialized twice from `init(coder:)`
        // return existing webView if webView already added
        let views = self.subviews.filter {$0 is JTACMonthView } as! [JTACMonthView]
        if views.count != 0 {
            return views.first!
        }
        
        let flow = UICollectionViewFlowLayout()
        flow.scrollDirection = .horizontal
        let cview = JTACMonthView(frame: .zero)
        self.addSubview(cview)
        return cview
        }()
    
    
    
    override func addLayoutRules() {
        
    
        calendarView.calendarDelegate = self
        calendarView.calendarDataSource = self
        calendarView.scrollDirection = UICollectionView.ScrollDirection.horizontal
        
        
        calendarView.register(DayCell.self, forCellWithReuseIdentifier: "day")
        calendarView.register(CLHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
        calendarView.minimumLineSpacing = 0.5/UIScreen.main.scale
        calendarView.minimumInteritemSpacing = 0.5/UIScreen.main.scale
        
        calendarView.isPagingEnabled = true
        calendarView.showsHorizontalScrollIndicator = false
    
        
        self.backgroundColor = .white
        self.eelay = [
            [calendarView,[ee.T.L.B.R],"\(Swidth + 10)",Swidth],
        ]
     
        
        self.backgroundColor = UIColor(shex: "#ca191d")
        calendarView.backgroundColor = UIColor(shex:"#cccccc")

        calendarView.reloadData()
    }
    
    
    @objc func canle() {
//        self.dismiss(animated: true, completion: nil)
    }
    
    
    open func didSelect(date:Date) {
        self.confirmDate(date)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()

        
        let dates = DataNode.path(node: "values", mo.model, value: NSMutableArray())
        var events = [NSMutableDictionary]()
        var date_vs = [Date]()
        dates.listObj { (one:NSMutableDictionary) in
            events.append(one)
            guard let d = DataNode<Date>.path(node: "value", one)else{return}
            date_vs.append(d)
            
        }
        calendarView.selectDates(date_vs)
        
        if date_vs.count > 0 {
            calendarView.scrollToHeaderForDate(date_vs[0])
            //            calendarView.scrollToDate(date_vs[0], triggerScrollToDateDelegate: true, animateScroll: false, preferredScrollPosition: nil, completionHandler: nil)
            return
        }
        guard let to_date = self.scrollToedDate else {
            return
        }
        calendarView.scrollToHeaderForDate(to_date)
        //         calendarView.scrollToDate(to_date, triggerScrollToDateDelegate: true, animateScroll: false, preferredScrollPosition: nil, completionHandler: nil)
        
        
        
    }
    
    
}


extension OneDayCalendarView:JTACMonthViewDelegate,JTACMonthViewDataSource
{
  
    
    
    //    func sizeOfDecorationView(indexPath: IndexPath) -> CGRect {
    //        return [0,0,Swidth,50]
    //    }
    
    func calendar(_ calendar: JTACMonthView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTACDayCell {
        let myCustomCell = calendar.dequeueReusableCell(withReuseIdentifier: "day", for: indexPath) as! DayCell
        myCustomCell.isSelectedCell = cellState.isSelected
        myCustomCell.titleL.text = cellState.text
        if !validSelectCheck(date){
            myCustomCell.haveEvent = false
        }
        else{
            myCustomCell.haveEvent = true
        }
        
        
        if cellState.dateBelongsTo == .thisMonth {
            //            myCustomCell.titleL.textColor = UIColor(shex: "#ca191d")
        } else {
            myCustomCell.titleL.textColor = UIColor(shex: "#eee")
        }
        
        return myCustomCell
    }
    
    
    
    func calendar(_ calendar: JTACMonthView, willDisplay cell: JTACDayCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) {
        let myCustomCell = cell as! DayCell
        myCustomCell.isSelectedCell = cellState.isSelected
        myCustomCell.titleL.text = cellState.text
        if !validSelectCheck(date){
            myCustomCell.haveEvent = false
        }
        else{
            myCustomCell.haveEvent = true
        }
        
        
        if cellState.dateBelongsTo == .thisMonth {
//            myCustomCell.titleL.textColor = UIColor(shex: "#ca191d")
        } else {
            myCustomCell.titleL.textColor = UIColor(shex: "#eee")
        }
        
    }
    
    
    internal func calendarSizeForMonths(_ calendar: JTACMonthView?) -> MonthSize? {
        return MonthSize(defaultSize:  60, months: [60: [.feb, .apr]])
    }
    
    
    func configureCalendar(_ calendar: JTACMonthView) -> ConfigurationParameters {
        let formatter = DateFormatter()
        let today = Date()
        let year_str = today["yyyy"]
        var today_strs = today["yyyy MM dd"].components(separatedBy: " ")
        today_strs.remove(at: 0)
        today_strs.insert("\(Int(year_str)!+1)", at: 0)
        
        formatter.dateFormat = "yyyy MM dd"
        
        //        let monthSize = MonthSize(defaultSize: 50, months: [75: [.feb, .apr]])
        
        
        let endDate = formatter.date(from: today_strs.joined(separator: " "))! // You can use date generated from a formatter
        let startDate = Date()                                // You can also use dates created from this function
        
        let parameters = ConfigurationParameters(
            startDate: startDate,  // This is manditory and must be supplied by you
            endDate: endDate,      // This is manditory and must be supplied by you
            numberOfRows: 6,                       // Default
            calendar: Calendar.current,            // Default
            generateInDates:  .forAllMonths,       // Default
            generateOutDates: .tillEndOfGrid,      // Default
            firstDayOfWeek:   .monday,             // Default
            hasStrictBoundaries: true
        )
        
        return parameters
    }
    
    
    func calendar(_ calendar: JTACMonthView, didDeselectDate date: Date, cell: JTACDayCell?, cellState: CellState) {
        guard let myCustomCell = cell as? DayCell else{return}
        myCustomCell.isSelectedCell = cellState.isSelected
    }
    
    func calendar(_ calendar: JTACMonthView, didSelectDate date: Date, cell: JTACDayCell?, cellState: CellState) {
        if self.validSelectCheck(date)
        {
            guard let myCustomCell = cell as? DayCell else{return}
            myCustomCell.isSelectedCell = cellState.isSelected
            didSelect(date: date)
        }
        else{
            calendar.deselectDates(from: date, to: date, triggerSelectionDelegate: true)
        }
    }
    
    
    
    
    func calendar(_ calendar: JTACMonthView, headerViewForDateRange range: (start: Date, end: Date), at indexPath: IndexPath) -> JTACMonthReusableView {
        let header = calendar.dequeueReusableJTAppleSupplementaryView(withReuseIdentifier: "header", for: indexPath)
        if let c_header = header as? CLHeaderView{
            c_header.titleL.text = range.start["YYYY年MM月"]
        }
        return header
    }
    
    
}



fileprivate class CLHeaderView: JTACMonthReusableView {
    let titleL = UILabel()
    let selectView = UIView()
    
    let weeksView = UIStackView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addLayoutRules()
    }
    
    func addLayoutRules() {
        eelay = [
            [selectView,[ee.T.L.B.R]],
            [weeksView,[ee.L.B.R],"20"],
            [titleL,[weeksView,ee.T,ee.B,-8],[ee.L.R,[10,-10]]],
        ]
        selectView.backgroundColor = UIColor(shex: "#ca191d")
        _ = titleL.ui.cl_fff.center.font20.text(hex: "#fffa")
        
        weeksView.axis = .horizontal
        weeksView.backgroundColor = UIColor(shex: "#0008")
        weeksView.distribution = .fillEqually
        let weeks = ["一","二","三","四","五","六","日"]
        let  ws = weeks.map { (str) -> UILabel in
            let  one = UILabel()
            one.ui.center.text(hex: "#eee8").bfont13.text("\(str)")
            return one
        }
        for oe in ws
        {
            weeksView.addArrangedSubview(oe)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}


fileprivate class DayCell:JTACDayCell {
    
    let titleL = UILabel()
    let infoL = UILabel()
    let selectView = UIView()
    
    var eventV = UIView()
    
    var haveEvent:Bool = false
    {
        didSet{
            updateDisplay()
        }
    }
    
    func updateDisplay() {
        if haveEvent{
            if isSelectedCell{
                eventV.backgroundColor = UIColor.main_color
                titleL.textColor = .white
            }
            else{
                eventV.backgroundColor = UIColor(shex:"\(UIColor.main_hex)33")
                titleL.textColor = UIColor(shex:UIColor.main_hex)
            }
        }
        else{
            eventV.backgroundColor = UIColor(shex:"#fff")
            titleL.textColor = UIColor(shex:"#aaa")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addLayoutRules()
    }
    
    func addLayoutRules() {
        self.backgroundColor = UIColor(shex: "#fff")
        contentView.eelay = [
            [eventV,"30",30,[ee.X.Y]],
            [selectView,[ee.T.L.B.R,[-1,-1,1,1]]],
            [titleL,[ee.X.Y]],
        ]
        eventV.bsui.background(hex: UIColor.main_hex).set(radius: 15, width: nil, color: nil)
//        eventV.alpha = 0
        contentView.clipsToBounds = true
        
        selectView.backgroundColor = UIColor(shex: "#fff0")
        _ = titleL.ui.cl_fff.center
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    
    open var isSelectedCell = false{
        didSet{
            if isSelectedCell
            {
                self.didSelect()
            }
            else{
                self.disSelect()
            }
        }
        
    }
//    override var isSelected:Bool{
//        set{
//            super.isSelected = newValue
//            if newValue{
//                self.didSelect()
//            }
//            else{
//                self.disSelect()
//            }
//
//        }
//        get{
//            return super.isSelected
//        }
//    }
    
    func didSelect() {
        updateDisplay()

    }
    
    func disSelect() {
        updateDisplay()
    }
    
    
}

